/**
 * This file contains the common middleware used by your routes.
 *
 * Extend or replace these functions as your application requires.
 *
 * This structure is not enforced, and just a starting point. If
 * you have more middleware you may want to group it as separate
 * modules in your project's /lib directory.
 */
var _ = require('lodash');
var keystone = require('keystone');

/**
 Initialises the standard view locals

 The included layout depends on the navLinks array to generate
 the navigation in the header, you may wish to change this array
 or replace it with your own templates / logic.
 */
exports.initLocals = function (req, res, next) {
	res.locals.navLinks = [
		{label: 'Home', key: 'home', href: '/'},
		{label: 'Blog', key: 'blog', href: '/blog'},
		{label: 'Gallery', key: 'gallery', href: '/gallery'},
		{label: 'Contact', key: 'contact', href: '/contact'},
	];
	res.locals.user = req.user;
	next();
};


/**
 Fetches and clears the flashMessages before a view is rendered
 */
exports.flashMessages = function (req, res, next) {
	var flashMessages = {
		info: req.flash('info'),
		success: req.flash('success'),
		warning: req.flash('warning'),
		error: req.flash('error'),
	};
	res.locals.messages = _.some(flashMessages, function (msgs) {
		return msgs.length;
	}) ? flashMessages : false;
	next();
};


/**
 Prevents people from accessing protected pages when they're not signed in
 */
exports.requireUser = function (req, res, next) {
	if (!req.user) {
		req.flash('error', 'Please sign in to access this page.');
		res.redirect('/keystone/signin');
	} else {
		next();
	}
};
exports.requireUserSystem = function (req, res, next) {
	if (!req.user && 0) {
		req.flash('error', 'Please sign in to access this page.');
		res.redirect('/login');
	} else {
		next();
	}
};

//csrfSet
exports.csrfSet = function (req, res, next) {
	res.locals.csrf = {header: {}};
	res.locals.csrf.header[keystone.security.csrf.CSRF_HEADER_KEY] = keystone.security.csrf.getToken(req, res);
	next();
};

//crsfCheck

exports.crsfCheck = function (req, res, next) {
	// if (!keystone.security.csrf.validate(req)) {
	// 	return res.json({code:0,message:'非法请求'});
	// }
	next();
};
exports.captcha = function (req, res, next) {
	if (!req.body.captcha) {
		return res.json({code: 0, message: '请填写验证码'});
	}
	if(req.body.captcha != req.session.verifycode){
		return res.json({code: 0, message: '验证码错误'});
	}
	next();
};
